<template>
  <div class="article-list-container">
    <!-- 搜索功能区域 -->
    <el-form inline class="search-form">
      <el-form-item label="标题">
        <el-input v-model="searchParams.title" placeholder="请输入标题" clearable @clear="fetchArticleData"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchArticleData">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="success" @click="handleAdd">新增文章</el-button>
      </el-form-item>
    </el-form>

    <!-- 文章列表表格 -->
    <el-table :data="filteredArticleList" border style="width: 100%" v-loading="loading">
      <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
      <el-table-column prop="title" label="标题" width="200" align="center"></el-table-column>
      <el-table-column label="图片" width="200" align="center">
        <template slot-scope="scope">
          <div v-for="(image, index) in scope.row.imagesArray" :key="index">
            <img :src="image" alt="文章图片" style="width: 100px; height: auto; margin: 5px 0;" />
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="content" label="文章内容" width="200" align="center">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" :content="scope.row.content" placement="top-start">
            <div class="content-preview">{{ scope.row.content }}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="liked" label="点赞数量" width="100" align="center"></el-table-column>
      <el-table-column prop="visited" label="访问量" width="100" align="center"></el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" align="center"></el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="text" class="delete-btn" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
      :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
      :total="total"></el-pagination>

    <!-- 新增文章信息的对话框 -->
    <el-dialog title="新增文章信息" :visible.sync="addDialogVisible" width="50%">
      <el-form :model="addForm" label-width="120px" ref="addForm" :rules="addFormRules">
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="addForm.title"></el-input>
        </el-form-item>
        <el-form-item label="上传图片" prop="images">
          <el-upload class="upload-demo" action="http://localhost:10010/admin/common/upload"
            :on-success="handleUploadSuccess" :headers="{ token: user.token }" :on-error="handleUploadError"
            :before-upload="beforeUpload" :file-list="fileList" list-type="picture-card" :limit="5"
            :on-exceed="handleExceed" :on-remove="handleRemove">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="文章内容" prop="content">
          <el-input type="textarea" v-model="addForm.content" :rows="4"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAdd">确定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑文章信息的对话框 -->
    <el-dialog title="编辑文章信息" :visible.sync="editDialogVisible" width="50%">
      <el-form :model="editForm" label-width="120px" ref="editForm" :rules="editFormRules">
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="editForm.title"></el-input>
        </el-form-item>
        <el-form-item label="上传图片" prop="images">
          <el-upload class="upload-demo" action="/admin/common/upload" :on-success="handleEditUploadSuccess"
            :on-error="handleUploadError" :before-upload="beforeUpload" :file-list="editFileList"
            list-type="picture-card" :limit="5" :on-exceed="handleExceed" :on-remove="handleEditRemove">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="文章内容" prop="content">
          <el-input type="textarea" v-model="editForm.content" :rows="4"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEdit">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request';
export default {
  data() {
    return {
      user: JSON.parse(localStorage.getItem('user') || '{}'),
      searchParams: {
        title: "",
        page: 1,
        pageSize: 10,
      },
      articleList: [],
      total: 0,
      currentPage: 1,
      pageSize: 10,
      loading: false,
      addDialogVisible: false,
      editDialogVisible: false,
      addForm: {
        title: "",
        images: [],
        content: "",
      },
      editForm: {
        id: null,
        title: "",
        images: [],
        content: "",
      },
      addFormRules: {
        title: [{ required: true, message: "请输入文章标题", trigger: "blur" }],
        images: [{ required: true, message: "请上传图片", trigger: "change" }],
        content: [
          { required: true, message: "请输入文章内容", trigger: "blur" },
        ],
      },
      editFormRules: {
        title: [{ required: true, message: "请输入文章标题", trigger: "blur" }],
        images: [{ required: true, message: "请上传图片", trigger: "change" }],
        content: [
          { required: true, message: "请输入文章内容", trigger: "blur" },
        ],
      },
      fileList: [],
      editFileList: [],
    };
  },
  computed: {
    // 过滤掉 delFlag 为 1 的数据，并解析图片字符串
    filteredArticleList() {
      return this.articleList.map((item) => ({
        ...item,
        imagesArray: item.images ? item.images.split(",") : [],
      }));
    },
  },
  created() {
    this.fetchArticleData();
  },
  methods: {
    // 获取文章数据
    fetchArticleData() {
      this.loading = true;
      this.searchParams.page = this.currentPage;
      this.searchParams.pageSize = this.pageSize;

      request
        .get("/admin/article/pageSearch", { params: this.searchParams })
        .then((response) => {
          if (response && response.code === 1) {
            this.articleList = response.data.records || [];
            this.total = response.data.total || 0;
          } else {
            this.$message.error("获取文章数据失败：" + response.message);
          }
        })
        .catch((error) => {
          console.error("获取文章数据失败：", error);
          this.$message.error("获取文章数据失败：" + error.message);
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 每页显示记录数改变时的处理
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.fetchArticleData(); // 重新获取数据
    },
    // 当前页码改变时的处理
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.fetchArticleData(); // 重新获取数据
    },
    // 新增文章
    handleAdd() {
      this.addForm = {
        title: "",
        images: [],
        content: "",
      };
      this.fileList = [];
      this.addDialogVisible = true;
    },
    // 提交新增
    submitAdd() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          const formData = {
            title: this.addForm.title,
            images: this.addForm.images,
            content: this.addForm.content,
          };

          request
            .post("/admin/article/create", formData)
            .then((response) => {
              if (response && response.code === 1) {
                this.$message.success("文章新增成功");
                this.addDialogVisible = false;
                this.fetchArticleData(); // 刷新列表
              } else {
                this.$message.error("文章新增失败：" + response.message);
              }
            })
            .catch((error) => {
              console.error("文章新增失败：", error);
              this.$message.error("文章新增失败：" + error.message);
            });
        } else {
          this.$message.error("表单验证失败，请检查输入");
        }
      });
    },
    // 文件上传成功
    handleUploadSuccess(response, file) {
      if (response && response.code === 1) {
        this.addForm.images.push(response.data); // 将上传后的图片路径添加到数组
        this.addForm.file = file; // 保存文件对象
        this.$message.success("图片上传成功");
        console.log(this.addForm);
      } else {
        this.$message.error("图片上传失败：" + response.message);
      }
    },
    // 文件上传失败
    handleUploadError(err, file) {
      this.$message.error("图片上传失败：" + err.message);
    },
    // 文件上传前的校验
    beforeUpload(file) {
      const isImage = file.type.startsWith("image/");
      if (!isImage) {
        this.$message.error("只能上传图片文件");
        return false;
      }
      return true;
    },
    // 文件超出限制
    handleExceed() {
      this.$message.warning("最多只能上传5张图片");
    },
    // 文件移除
    handleRemove(file, fileList) {
      const index = this.addForm.images.indexOf(file.url);
      if (index !== -1) {
        this.addForm.images.splice(index, 1);
      }
    },
    // 编辑文章
    handleEdit(row) {
      this.editForm = { ...row };
      this.editForm.images = row.images ? row.images.split(",") : [];
      this.editFileList = this.editForm.images.map((url) => ({ url }));
      this.editDialogVisible = true;
    },
    // 提交编辑
    submitEdit() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          const formData = {
            id: this.editForm.id,
            title: this.editForm.title,
            images: this.editForm.images.join(","),
            content: this.editForm.content,
          };

          request
            .put("/admin/article/update", formData)
            .then((response) => {
              if (response && response.code === 1) {
                this.$message.success("文章更新成功");
                this.editDialogVisible = false;
                this.fetchArticleData(); // 刷新列表
              } else {
                this.$message.error("文章更新失败：" + response.message);
              }
            })
            .catch((error) => {
              console.error("文章更新失败：", error);
              this.$message.error("文章更新失败：" + error.message);
            });
        } else {
          this.$message.error("表单验证失败，请检查输入");
        }
      });
    },
    // 编辑时文件上传成功
    handleEditUploadSuccess(response, file) {
      if (response && response.code === 1) {
        this.editForm.images.push(response.data.url); // 将上传后的图片路径添加到数组
        this.$message.success("图片上传成功");
      } else {
        this.$message.error("图片上传失败：" + response.message);
      }
    },
    // 编辑时文件移除
    handleEditRemove(file, fileList) {
      const index = this.editForm.images.indexOf(file.url);
      if (index !== -1) {
        this.editForm.images.splice(index, 1);
      }
    },
    // 删除文章
    handleDelete(row) {
      this.$confirm("此操作将永久删除该文章, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          request
            .delete("/admin/article/delete", { params: { id: row.id } })
            .then((response) => {
              if (response && response.code === 1) {
                this.$message.success("文章删除成功");
                this.fetchArticleData(); // 刷新列表
              } else {
                this.$message.error("文章删除失败：" + response.message);
              }
            })
            .catch((error) => {
              console.error("文章删除失败：", error);
              this.$message.error("文章删除失败：" + error.message);
            });
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },
  },
};
</script>

<style scoped>
.article-list-container {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
}

.delete-btn {
  color: #f56c6c;
}

.content-preview {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 180px;
}
</style>